<template>
  <ContentWrap>
    <el-main class="p-3 app-block">
      <el-form :model="values" ref="formRef" :rules="rules" label-width="200px">
        <el-row>
          <el-col :span="24">
            <el-form-item prop="otherConfig.ipLimitOpen">
              <template #label><label-tip message="cms.config.other.ipLimitOpen" /></template>
              <el-select v-model="values.otherConfig.ipLimitOpen">
                <el-option
                  v-for="n in [0, 1]"
                  :key="n"
                  :value="n"
                  :label="$t(`cms.config.other.ipLimitOpen.${n}`)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="otherConfig.ipLimitType">
              <template #label><label-tip message="cms.config.other.ipLimitType" /></template>
              <el-select v-model="values.otherConfig.ipLimitType">
                <el-option
                  v-for="n in [1, 2]"
                  :key="n"
                  :value="n"
                  :label="$t(`cms.config.other.ipLimitType.${n}`)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="otherConfig.ipErrorByHourLimit"
              :rules="{ required: true, message: () => $t('common.required') }"
            >
              <template #label
                ><label-tip message="cms.config.other.ipErrorByHourLimit" help
              /></template>
              <el-input-number
                v-model="values.otherConfig.ipErrorByHourLimit"
                :min="0"
                :max="100000"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              prop="otherConfig.ipAttachByHourLimit"
              :rules="{ required: true, message: () => $t('common.required') }"
            >
              <template #label
                ><label-tip message="cms.config.other.ipAttachByHourLimit" help
              /></template>
              <el-input-number
                v-model="values.otherConfig.ipAttachByHourLimit"
                :min="0"
                :max="100000"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="otherConfig.ipUrlLimitTimes"
              :rules="{ required: true, message: () => $t('common.required') }"
            >
              <template #label
                ><label-tip message="cms.config.other.ipUrlLimitTimes" help
              /></template>
              <el-input-number v-model="values.otherConfig.ipUrlLimitTimes" :min="0" :max="10000" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              prop="otherConfig.ipUrlMaxExceedLimitTimes"
              :rules="{ required: true, message: () => $t('common.required') }"
            >
              <template #label
                ><label-tip message="cms.config.other.ipUrlMaxExceedLimitTimes" help
              /></template>
              <el-input-number
                v-model="values.otherConfig.ipUrlMaxExceedLimitTimes"
                :min="0"
                :max="10000"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider />

        <el-row>
          <el-col :span="24">
            <el-form-item prop="adminIpConfig.limitOpen">
              <template #label><label-tip message="cms.config.adminIpConfig.limitOpen" /></template>
              <el-select v-model="values.adminIpConfig.limitOpen">
                <el-option
                  v-for="n in [0, 1]"
                  :key="n"
                  :value="n"
                  :label="$t(`cms.config.other.ipLimitOpen.${n}`)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item prop="adminIpConfig.ips">
              <template #label><label-tip message="cms.config.adminIpConfig.ips" help /></template>
              <el-input v-model="values.adminIpConfig.ips" @input="validateIP" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="adminIpConfig.ipRanges">
              <template #label
                ><label-tip message="cms.config.adminIpConfig.ipRanges" help
              /></template>
              <XButton type="primary" :title="t('cms.common.addLine')" @click="handleAddLine()" />
              <el-divider />
              <el-row v-for="(ipItem, index) in values.adminIpConfig.ipRanges" :key="index">
                <el-col :span="16">
                  <label-tip message="cms.config.adminIpConfig.ipRanges.from" /><el-input
                    v-model="ipItem.from"
                    @input="validateRangeIP(ipItem.from)"
                  />
                  <label-tip message="cms.config.adminIpConfig.ipRanges.to" />
                  <el-input v-model="ipItem.to" @input="validateRangeIP(ipItem.to)" />
                </el-col>
                <XButton
                  type="primary"
                  link="true"
                  :title="t('action.del')"
                  @click="handleDelLine(index)"
                />
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </ContentWrap>
</template>
<script setup lang="ts" name="SystemConfig">
import { ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import * as SystemConfigApi from '@/api/cms/system/index'
import { initConfig } from '@/store/modules/cmsGlobalConfig'

const formRef = ref<FormInstance>()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const config = ref<any>({})
const values = ref<any>({
  otherConfig: {},
  adminIpConfig: {
    ips: [],
    ipRanges: [
      {
        from: '',
        to: ''
      }
    ]
  }
})
const handleAddLine = () => {
  values.value.adminIpConfig.ipRanges.push({ from: '', to: '' })
}
const handleDelLine = (index) => {
  values.value.adminIpConfig.ipRanges.splice(
    values.value.adminIpConfig.ipRanges.findIndex((item) => item.index === index),
    1
  )
}
const fetchConfig = async () => {
  config.value = await SystemConfigApi.getConfig()
  values.value = config.value
}

const validateIP = () => {
  var iparr = values.value.adminIpConfig.ips.split(',')
  for (var i = 0; i < iparr.length; i++) {
    let ip = iparr[i]
    if (!isIP(ip)) {
      message.error(`ip只能填写ipv4 ${ip}`)
    }
  }
  values.value.adminIpConfig.ips = iparr
}
const validateRangeIP = (val) => {
  let ip = val
  if (!isIP(ip)) {
    message.error(`ip只能填写ipv4 ${ip}`)
  }
}
function isIP(str) {
  const ipRegex =
    /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  return ipRegex.test(str)
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleSystemConfigUpdate()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleSystemConfigUpdate = async () => {
  // 设置数据
  await SystemConfigApi.updateConfigApi(values.value)
  fetchConfig()
  initConfig()
  message.success(t('common.updateSuccess'))
}

// ========== 初始化 ==========
onMounted(async () => {
  fetchConfig()
})
</script>
